var app = getApp();
var request = app.request;
var util = require('../../../utils/util.js');

const date = new Date()
const years = []
const months = []
const days = []
const hours = []
const minutes = []
var thisMon = date.getMonth();
var thisDay = date.getDate() + 1;
var thisHours = date.getHours();
var thisMinutes = date.getMinutes();
for (let i = 2017; i <= date.getFullYear() + 1; i++) {
	years.push(i)
}

for (let i = date.getMonth(); i <= 11; i++) {
	var k = i;
	if (0 <= i && i < 9) {
		k = "0" + (i + 1);
	} else {
		k = (i + 1);
	}
	months.push(k)
}
if (0 <= thisMon && thisMon < 9) {
	thisMon = "0" + (thisMon + 1);
} else {
	thisMon = (thisMon + 1);
}
if (0 <= thisDay && thisDay < 10) {
	thisDay = "0" + thisDay;
}

if (thisMinutes < 10) {
	thisMinutes = "0" + thisMinutes;
}

var totalDay = mGetDate(date.getFullYear(), thisMon);
for (let i = 1; i <= 31; i++) {
	var k = i;
	if (0 <= i && i < 10) {
		k = "0" + i
	}
	days.push(k)
}

for (let i = 0; i <= 23; i++) {
	var k = i;
	if (0 <= i && i < 10) {
		k = "0" + i
	}
	hours.push(k)
}
for (let i = 0; i <= 59; i++) {
	var k = i;
	if (0 <= i && i < 10) {
		k = "0" + i
	}
	minutes.push(k)
}

function mGetDate(year, month) {
	var d = new Date(year, month, 0);
	return d.getDate();
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: app.globalData.setting.url,
    userInfo: null,
    mobile: '',
    eatType: 1,
    orderPrices: null,
    timeType: 1,
    showTakeawayType: false,
    time: null,
    goods: null,
    order: null,
    coupons: null, //可用的优惠券
		coupon: null, //已使用的优惠券     
		payWithUserMoney: true, //是否使用余额支付
		payWithPoints: true, //是否使用积分支付
		maxWord: 0,
		enterAddressPage: false,
		firstEnter: true, //是否第一次进入页面
		invoice_title: '',
		taxpayer: '',
		invoice_desc: '不开发票',
		text: '不开发票',
		formData: {
			pay_points: '',
			user_money: '',
			paypwd: '',
			user_note: '',
		},
		shopList: null,
		shop_id: null,
		shop_name: '选择门店',
		shop_address: '',
		shop_image: '/public/images/minapp/add-img.png',
		shop: [],
		items: [{
			name: '快速配送',
			value: '工作日、双休日与节假日均可送货',
			checked: 'true'
		}, ],
		submit_datas: {
			shop_id: '', //自提id
			submit_text: '', //页面展示自提时间
			submit_address: '', //页面展示自提地点
			name: '', //自提人
			mobile: '', //自提联系方式
			time: '', //自提时间
		},
		submit: false,
		is_set: false,
		submit_heigth_css: 240,
		selected: 0,
		checkTime: date.getFullYear() + "-" + thisMon + "-" + thisDay + " " + thisHours + ":" + thisMinutes,
		//checkTime:'2023-08-30 12:00', 
		//---时间控件参数
		flag: true,
		years: years,
		year: date.getFullYear(),
		months: months,
		month: thisMon,
		days: days,
		day: thisDay,
		value: [1, 0, thisDay - 1, thisHours, thisMinutes],
		hours: hours,
		hour: thisHours,
		minutes: minutes,
		minute: thisMinutes,
		weekDay: ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    app.getUserInfo(function (userInfo) {
      that.setData({ userInfo: userInfo });
    }, true);
    this.setData({
			goods: options,
		});
    this.requestCart2();
  },

  requestCart2: function(address) {
		var that = this;
		var data = {
      type: 2,
    };
		if (this.data.goods.action) { //商品立即购买跳转
			data = {
        type: 2,
				goods_id: this.data.goods.goods_id,
				item_id: this.data.goods.item_id,
				goods_num: this.data.goods.goods_num,
				action: this.data.goods.action,
			};
		}
		request.get('/api/cart/cart2', {
			failRollback: true,
			data: data,
			success: function(res) {
				var j = 0;
				for (var i of res.data.result.cartList) {
					res.data.result.cartList[j].member_goods_price = parseFloat(i
						.member_goods_price).toFixed(2).toString().split('.')
					j++
				}
				that.setData({
					order: res.data.result
				});
				// if (res.data.result.userCouponNum.usable_num > 0) {
				// 	that.setData({
				// 		coupons: res.data.result.userCartCouponList
				// 	});
				// } else {
				// 	that.setData({
				// 		coupons: []
				// 	});
				// }
					
					// if (address) {
					// 	that.setData({
					// 		'order.userAddress': address
					// 	});
					// 	that.getShopList();
					// 	if (that.checkAddressList()) {
					// 		that.calculatePrice();
					// 	}
					// } else if (wx.getStorageSync('goodsInfo:goodsInfo:address')) {
					// 	that.setData({
					// 		'order.userAddress': wx.getStorageSync(
					// 			'goodsInfo:goodsInfo:address')
					// 	});
					// 	that.getShopList();
					// 	wx.removeStorageSync('goodsInfo:goodsInfo:address');
					// 	if (that.checkAddressList()) {
							that.calculatePrice();
					// 	}
					// } else {
					// 	that.getDefaultAddress();
					// }
			},
			failStatus: function(res) {
				if (res.data.status == 0) {
					wx.showModal({
						title: res.data.msg,
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								wx.navigateBack();
							}
						},
						fail: function() {
							wx.navigateBack();
						}
					});
				} else if (res.data.status == -1) {
					that.setData({
						order: null
					});
					// that.checkAddressList();
				}
				return false;
			}
		});
  },
  
  /** 请求计算价格 */
	calculatePrice: function(formData, submitOrder) {
		var that = this;
		if (typeof formData == 'undefined') {
			formData = that.data.formData;
		} else {
			that.data.formData = formData;
		}
		var postData;
		var submitTime = '';
		if (this.data.submit_datas.time != '') {
			submitTime = this.data.submit_datas.time.replace(/-/g, '/');
			submitTime = Date.parse(new Date(submitTime)) / 1000
		}
		// if (!that.data.order.userAddress) {
		// 	return app.showTextWarining('请添加地址', function() {
		// 		that.setData({
		// 			enterAddressPage: true
		// 		})
		// 		wx.navigateTo({
		// 			url: '../../user/address_list/address_list',
		// 		})
		// 	});
    // }
    if(that.data.timeType == 2&&that.data.eatType == 2&&!that.data.time) {
      app.showTextWarining("请输入预约到店时间");
      return;
    }
    var dates = that.data.year+'-'+that.data.month+'-'+(that.data.day-1);
		if (this.data.goods.action) {
			postData = {
        type: 2,
        reservation_time: dates + ' ' + ((that.data.timeType == 2&&that.data.eatType == 2) ? that.data.time : ''),
        meal_type: that.data.eatType,
				address_id: 0,
				invoice_title: that.data.invoice_title ? that.data.invoice_title : '',
				taxpayer: that.data.taxpayer ? that.data.taxpayer : '',
				invoice_desc: that.data.invoice_desc ? that.data.invoice_desc : '',
				pay_points: formData.pay_points ? formData.pay_points : this.data.available_integral,
				user_money: formData.user_money ? formData.user_money : 0,
				act: submitOrder ? 'submit_order' : 'order_price',
				user_note: formData.user_note,
				coupon_id: that.data.coupon ? that.data.coupon.id : '',
				goods_id: this.data.goods.goods_id,
				item_id: this.data.goods.item_id,
				goods_num: this.data.goods.goods_num,
				action: this.data.goods.action,
				shop_id: this.data.shop_id,
				take_time: submitTime,
				consignee: '无', //this.data.submit ? this.data.submit_datas.name : '',
				mobile: that.data.mobile, //this.data.submit ? this.data.submit_datas.mobile : '',
				from_terminal: 'miniapp',
			};
			postData = submitOrder ? that.getBespeakFormData(postData) : postData
		} else {
			postData = {
        type: 2,
        reservation_time: dates + ' ' + ((that.data.timeType == 2&&that.data.eatType == 2) ? that.data.time : ''),
        meal_type: that.data.eatType,
				address_id: 0,
				invoice_title: that.data.invoice_title ? that.data.invoice_title : '',
				taxpayer: that.data.taxpayer ? that.data.taxpayer : '',
				invoice_desc: that.data.invoice_desc ? that.data.invoice_desc : '',
				pay_points: formData.pay_points ? formData.pay_points : 0,
				user_money: formData.user_money ? formData.user_money : 0,
				act: submitOrder ? 'submit_order' : 'order_price',
				user_note: formData.user_note,
				coupon_id: that.data.coupon ? that.data.coupon.id : '',
				shop_id: this.data.shop_id,
				take_time: submitTime,
				consignee: '无', //this.data.submit ? this.data.submit_datas.name : '',
				mobile: that.data.mobile, //this.data.submit ? this.data.submit_datas.mobile : '',
				from_terminal: 'miniapp',
			};
		}
		request.post('/api/cart/cart3', {
			data: postData,
			success: function(res) {
				if (res.data.result.integral_msg) {
					app.showTextWarining(res.data.result.integral_msg)
					// that.setData({
					// 	available_integral: res.data.result.pay_points
					// })
        }
        console.log(submitOrder)
				if (!submitOrder) {
					that.setData({
						orderPrices: res.data.result
					})
					return;
				}
				wx.removeStorageSync('bespeakFormData');
				wx.removeStorageSync('bespeak_template_unit');
				var order_type = that.data.order.cartList[0].prom_type;
				if (that.data.submit) {
					order_type = 9
				}
				if (that.data.orderPrices.order_amount <= 0) {
					wx.setStorageSync('order:order_list:update', true);
					var url_param = (that.data.order.cartList[0]['goods']['is_virtual'] == 2) ?
						'&goods_name=' + that.data.order.cartList[0]['goods']['goods_name'] +
						'&take_time=' + postData.take_time : ''
					wx.redirectTo({
						url: '/pages/payment/payment/payment?order_sn=' + res.data
							.result + '&order_amount=' + that.data.orderPrices
							.total_amount + '&order_type=' + order_type + url_param
					});
				} else {
					var params = (that.data.order.cartList[0]['goods']['is_virtual'] == 2) ? {
						order_sn: res.data.result,
            order_type: 7,
            type: 2,
						goods_name: that.data.order.cartList[0]['goods']['goods_name'],
            take_time: postData.take_time,
            eatType: that.data.eatType
					} : {
            type: 2,
						order_sn: res.data.result,
            order_type: order_type,
            eatType: that.data.eatType
					};

					var url = '/pages/cart/cart4/cart4?' + util.Obj2Str(params);
					wx.redirectTo({
						url: url
					});
				}
			},
			failStatus: function(res) {
				if (res.data.msg == '请先设置支付密码') {
					wx.showModal({
						title: '请先设置支付密码',
						success: function(res) {
							if (res.confirm) {
								wx.navigateTo({
									url: '/pages/user/userinfo/userinfo'
								});
							} else {
								wx.navigateBack();
							}
						},
						fail: function() {
							wx.navigateBack();
						}
					});
				} else if (res.data.status == -5) {
					that.setData({
						available_integral: ''
					})
				} else if (res.data.status == -6) {
					that.setData({
						available_balance: ''
					})
				}
			}
		});
	},

  changeEatType(e) {
    this.setData({
      eatType: e.currentTarget.dataset.index
    })
    if(e.currentTarget.dataset.index==2) {
      this.openDialog();
    }
  },

  changeTimeType(e) {
    this.setData({
      timeType: e.currentTarget.dataset.index
    })
  },

  openDialog() {
    this.setData({
      showTakeawayType: true
    })
  },

  closeDialog() {
    this.setData({
      showTakeawayType: false
    })
  },

  submitOrder() {
    this.calculatePrice(this.data.formData, 'submit_order');
    // wx.navigateTo({
    //   url: '/subPages/pages/order/orderDetail/orderDetail',
    // })
  },

  bindTimeChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },

  changeMobile(e) {
    this.setData({
      mobile: e.detail.value
    })
  }
})